import {proxyModule} from 'tscommon/ts/vue/vm.ext';
import {TestFetch,TestAdd,TestModify} from 'tsdomain/Test';
import {fetchData,isError} from 'tscommon/ts/tools/domain';

import {ValidTools} from 'tscommon/ts/tools/Valid.tools';
import {Lang} from 'tscommon/ts/lang.ts';

const ValidCfg = new ValidTools([
  {field:"name",desc:Lang.Name,valids:["required"]},
]);

const {data,onCreate,onDestroy,onReady,onRefresh,onShow,events} = proxyModule({
  data(){
    return {
      form:{
        id:"",
        name:""
      },
      valid:{},
      errorInfo:[]
    };
  },
  events:{
    async fetch(id:string){
      this.setter({'form.id':id});
      const resp =  await fetchData(TestFetch,{id});
      if(!resp.flag||resp.data==null){
        isError(resp,this);
        return false;
      }
      this.setter({'form':{id:resp.data.id,name:resp.data.name}});
      return true;
    },
    async testModify(){
      const [vFlag,result]=await ValidCfg.valid({...this.form});
      this.setter({valid:result});
      if(!vFlag){
        this.setter({errorInfo:[Lang.validFail]});
        return false;
      }
      const resp = this.form.id==null?await fetchData(TestAdd,{...this.form}):await fetchData(TestModify,{...this.form});
      if(!resp.flag||resp.data==null){
        isError(resp,this);
        return false;
      }
      return true;
    }
  }
});
export  {data,onCreate,onDestroy,onReady,onRefresh,onShow,events};